package sysytmRepo

import (
	"github.com/gin-gonic/gin"
	useragent "github.com/wenlng/go-user-agent"
	"gorm.io/gorm"
	"ruoyi/domain/entity/common"
	"ruoyi/domain/entity/response"
	"ruoyi/domain/entity/system"
	"ruoyi/domain/repository"
	"ruoyi/utils"
	"time"
)

type SysLoginInfoRepo struct {
	db *gorm.DB
}

func SysLoginInfoRepository(db *gorm.DB) *SysLoginInfoRepo {
	return &SysLoginInfoRepo{db}
}

var _ repository.SysLoginInfoRepository = &SysLoginInfoRepo{}

//分页查询
func (r *SysLoginInfoRepo) SelectLoginInfoList(params common.SearchTableDataParam) ([]system.SysLoginInfo, int64) {
	var pageNum = params.PageNum
	var pageSize = params.PageSize
	sysLoginInfo := params.Other.(system.SysLoginInfo)
	var ipaddr = sysLoginInfo.Ipaddr
	var userName = sysLoginInfo.UserName
	var status = sysLoginInfo.Status

	var orderByColumn = params.OrderByColumn
	var isAsc = params.IsAsc

	var beginTime = params.Params.BeginTime
	var endTime = params.Params.EndTime

	var total int64
	db := r.db.Model(system.SysLoginInfo{})

	if ipaddr != "" {
		db.Where("ipaddr like ?", ipaddr+"%")
	}
	if status != "" {
		db.Where("status = ?", status)
	}
	if userName != "" {
		db.Where("user_name like ?", userName+"%")
	}
	if beginTime != "" {
		//Loc, _ := time.LoadLocation("Asia/Shanghai")
		//startTime1, _ := time.ParseInLocation(constants.DateFormat, beginTime, Loc)
		//endTime = endTime + " 23:59:59"
		//endTime1, _ := time.ParseInLocation(constants.TimeFormat, endTime, Loc)
		startTime1, endTime1 := utils.GetBeginAndEndTime(beginTime, endTime)
		//db.Where("login_time >= ? and login_time <= ?", startTime1, endTime1)
		db.Where("login_time >= ?", startTime1)
		db.Where("login_time <= ?", endTime1)
	}
	if orderByColumn != "" {
		if "ascending" == isAsc {
			if "loginTime" == orderByColumn {
				db.Order("login_time DESC")
			}
			if "userName" == orderByColumn {
				db.Order("user_name DESC")
			}
		}
		if "descending" == isAsc {
			if "loginTime" == orderByColumn {
				db.Order("login_time ASC")
			}
			if "userName" == orderByColumn {
				db.Order("user_name ASC")
			}
		}
	}
	if err := db.Count(&total).Error; err != nil {
		return nil, 0
	}
	offset := (pageNum - 1) * pageSize
	var list []system.SysLoginInfo
	db.Order("info_id DESC").Offset(offset).Limit(pageSize).Find(&list)
	return list, total
}

func (r *SysLoginInfoRepo) LoginInfoAdd(context *gin.Context, param system.LoginParam, message string, loginSuccess bool) response.Response {
	status := "0"
	if !loginSuccess {
		status = "1"
	}

	userAgent := context.Request.Header.Get("User-Agent")
	os := useragent.GetOsName(userAgent)
	browser := useragent.GetBrowserName(userAgent)
	ip := utils.GetRemoteClientIp(context.Request)
	loginLocation := utils.GetRealAddressByIP(ip)

	info := system.SysLoginInfo{
		UserName:      param.UserName,
		Msg:           message,
		Ipaddr:        ip,
		LoginLocation: loginLocation,
		Browser:       browser,
		Os:            os,
		Status:        status,
		LoginTime:     time.Now(),
	}

	if err := r.db.Create(&info).Error; err != nil {
		return response.ReturnFailMsg(err.Error())
	}

	return response.ReturnSuccess("操作成功")
}

func (r *SysLoginInfoRepo) DelLoginLog(infoIdS []int) response.Response {
	if err := r.db.Model(&system.SysLoginInfo{}).Delete("info_id in (?)", infoIdS).Error; err != nil {
		return response.ReturnFailMsg(err.Error())
	}
	return response.ReturnSuccess("操作成功")
}

func (r *SysLoginInfoRepo) ClearLoginLog() response.Response {
	if err := r.db.Model(&system.SysLoginInfo{}).Raw("truncate table sys_logininfor").Find(system.SysLoginInfo{}).Error; err != nil {
		return response.ReturnFailMsg(err.Error())
	}
	return response.ReturnSuccess("操作成功")
}

func (r *SysLoginInfoRepo) UnlockByUserName(userName string) {
	/*在redis 里面删除*/
}
